/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.netbeans.modules.mercurial.ui.queues;

import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import static javax.swing.JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT;
import javax.swing.KeyStroke;
import org.netbeans.modules.spellchecker.api.Spellchecker;
import org.netbeans.modules.versioning.util.StringSelector;
import org.netbeans.modules.versioning.util.TemplateSelector;
import org.netbeans.modules.versioning.util.UndoRedoSupport;
import org.netbeans.modules.versioning.util.common.CommitMessageMouseAdapter;
import org.openide.util.NbBundle;

/**
 *
 * @author Tomas Stupka
 */
public class CommitPanel extends javax.swing.JPanel {
    private final QCreatePatchParameters parameters;
    private UndoRedoSupport um;

    /** Creates new form CommitPanel */
    public CommitPanel(QCreatePatchParameters parameters, String commitMessage, String patchName) {
        this.parameters = parameters;
        
        initComponents();
        boolean skipTemplates = false;
        if (patchName != null && !patchName.isEmpty()) {
            txtPatchName.setText(patchName);
            txtPatchName.setEditable(false);
            skipTemplates = true;
        }
        
        messageTextArea.setColumns(60);    //this determines the preferred width of the whole dialog
        messageTextArea.setLineWrap(true);
        messageTextArea.setRows(4);
        messageTextArea.setTabSize(4);
        messageTextArea.setWrapStyleWord(true);
        messageTextArea.setMinimumSize(new Dimension(100, 18));
        
        messageTextArea.getAccessibleContext().setAccessibleName(getMessage("ACSN_CommitForm_Message")); // NOI18N
        messageTextArea.getAccessibleContext().setAccessibleDescription(getMessage("ACSD_CommitForm_Message")); // NOI18N
        messageTextArea.addMouseListener(new CommitMessageMouseAdapter());
        
        Spellchecker.register (messageTextArea);  
        initCommitMessage(commitMessage, skipTemplates);
        
        cmbAuthor.setModel(parameters.createRecentUsersModel());

        initActions();
    }
    
    private void initCommitMessage (String commitMessage, boolean skipTemplates) {
        TemplateSelector ts = new TemplateSelector(parameters.getPreferences());
        if (commitMessage == null) {
            commitMessage = ""; //NOI18N
        }
        messageTextArea.setText(commitMessage);
        if (ts.isAutofill() && !skipTemplates) {
            messageTextArea.setText(ts.getTemplate());
        } else {
            String lastCommitMessage = parameters.getLastCanceledCommitMessage();
            if (lastCommitMessage.isEmpty() && new StringSelector.RecentMessageSelector(parameters.getPreferences()).isAutoFill()) {
                List<String> messages = parameters.getCommitMessages();
                if (messages.size() > 0) {
                    lastCommitMessage = messages.get(0);
                }
            }
            if (commitMessage.isEmpty() && !lastCommitMessage.isEmpty()) {
                messageTextArea.setText(lastCommitMessage);
            }
        }
        messageTextArea.selectAll();
    }
    
    @Override
    public void addNotify() {
        super.addNotify();
        if (um == null) {
            um = UndoRedoSupport.register(messageTextArea);
        }
    }

    @Override
    public void removeNotify() {
        // kind of a work-around, removeNotify is called even when a diff view is opened in the commit dialog
        // we may unregister only when the whole dialog is shut down
        if (getParent() == null || !getParent().isShowing()) {
            if (um != null) {
                um.unregister();
                um = null;
            }
        }
        super.removeNotify();
    }
        
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        messageLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        templatesLabel = parameters.getMessagesTemplateLink(messageTextArea);
        recentLabel = parameters.getRecentMessagesLink(messageTextArea);
        jLabel1 = new javax.swing.JLabel();

        messageLabel.setLabelFor(messageTextArea);
        org.openide.awt.Mnemonics.setLocalizedText(messageLabel, org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.messageLabel.text")); // NOI18N

        messageTextArea.setColumns(20);
        messageTextArea.setRows(5);
        jScrollPane1.setViewportView(messageTextArea);

        org.openide.awt.Mnemonics.setLocalizedText(templatesLabel, org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.templatesLabel.text")); // NOI18N
        templatesLabel.setToolTipText(org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.templatesLabel.TTtext")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(recentLabel, org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.recentLabel.text")); // NOI18N
        recentLabel.setToolTipText(org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.recentLabel.TTtext")); // NOI18N

        jLabel1.setLabelFor(txtPatchName);
        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.jLabel1.text")); // NOI18N
        jLabel1.setToolTipText(org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.jLabel1.TTtext")); // NOI18N

        txtPatchName.setText(org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.txtPatchName.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(cbAuthor, org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.cbAuthor.text")); // NOI18N
        cbAuthor.setToolTipText(org.openide.util.NbBundle.getMessage(CommitPanel.class, "CommitPanel.cbAuthor.TTtext")); // NOI18N

        cmbAuthor.setEditable(true);
        cmbAuthor.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cbAuthor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cmbAuthor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPatchName, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 501, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(messageLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 382, Short.MAX_VALUE)
                        .addComponent(recentLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(templatesLabel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtPatchName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(messageLabel)
                    .addComponent(templatesLabel)
                    .addComponent(recentLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbAuthor)
                    .addComponent(cmbAuthor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    final javax.swing.JCheckBox cbAuthor = new javax.swing.JCheckBox();
    final javax.swing.JComboBox cmbAuthor = new javax.swing.JComboBox();
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel messageLabel;
    final javax.swing.JTextArea messageTextArea = new javax.swing.JTextArea();
    private javax.swing.JLabel recentLabel;
    private javax.swing.JLabel templatesLabel;
    final javax.swing.JTextField txtPatchName = new javax.swing.JTextField();
    // End of variables declaration//GEN-END:variables

    private String getMessage(String msgKey) {
        return NbBundle.getMessage(CommitPanel.class, msgKey);
    }

    private void initActions () {
        InputMap inputMap = getInputMap( WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
        ActionMap actionMap = getActionMap();
        Object action = recentLabel.getClientProperty("openAction");
        if (action instanceof Action) {
            inputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_R, KeyEvent.ALT_DOWN_MASK, false ), "messageHistory" ); //NOI18N
            actionMap.put("messageHistory", (Action) action); //NOI18N
        }
        action = templatesLabel.getClientProperty("openAction");
        if (action instanceof Action) {
            inputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_L, KeyEvent.ALT_DOWN_MASK, false ), "messageTemplate" ); //NOI18N
            actionMap.put("messageTemplate", (Action) action); //NOI18N
        }
    }

}
